package com.base.look.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.base.CBaseMvpFragment;
import com.base.commonlib.bean.StatEntity;
import com.base.commonlib.resh.api.RefreshLayout;
import com.base.commonlib.resh.footer.ClassicsFooter;
import com.base.commonlib.resh.header.ClassicsHeader;
import com.base.commonlib.resh.listener.OnRefreshLoadmoreListener;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.utils.ToastUtil;
import com.base.commonlib.widget.CommonDialog;
import com.base.look.R;
import com.base.look.act.SelectPopupWindow;
import com.base.look.adapter.LookAdapter2;
import com.base.look.bean.DataCenter;
import com.base.look.bean.LookListBean;
import com.base.look.bean.StatEntity2;
import com.base.look.databinding.FragmentLookBinding;
import com.base.look.presenter.LookPresenter;
import com.base.look.utils.CaremaPhotoUtils;
import com.base.look.utils.EmojiPanelView;
import com.base.look.utils.TextLinkifyUtils;
import com.base.look.view.LookView;
import com.base.video.java.MediaPlayerManager;
import com.base.video.java.VideoView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * Created by zw on 2020/2/28.
 * 看看列表x
 */
@SuppressWarnings("all")
public class LookFragment extends CBaseMvpFragment<LookPresenter> implements LookView {
    protected FragmentLookBinding mBinding;
    private LookAdapter2 lookAdapter;
    private BottomSheetDialog dialog;
    private int page = 1;
    private LookListBean.Rows.Comments comments;
    private LookListBean.Rows.Comments reply;
    private List<LookListBean.Rows> mData = new ArrayList<>();
    private Disposable disposable;
    private Disposable disposableEvent;
    private SelectPopupWindow selectPopupWindow;
    private LinearLayoutManager linearLayoutManager;
    private SensorEventListener mSensorEventListener;
    private SensorManager mSensorManager;

    @Override
    public void init() {
        mBinding = (FragmentLookBinding) mRootBinding;
        mBinding.smartRefreshLayout.setRefreshHeader(new ClassicsHeader(mContext));
        mBinding.smartRefreshLayout.setHeaderHeight(60);
        mBinding.smartRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        mPresenter = new LookPresenter(this, getActivity());
        mPresenter.start();


        if (("0").equals(mPresenter.mUser.getCanVerify())){
            mBinding.imgLeft.setVisibility(View.GONE);
        }else{
            mBinding.imgLeft.setVisibility(View.VISIBLE);
        }

        mBinding.imgLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/examine/look").navigation();
            }
        });
        /**
         * 添加
         */
        mBinding.imgRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ARouter.getInstance().build("/look/editlook").navigation();
                selectPopupWindow = new SelectPopupWindow(mContext);
                selectPopupWindow.showAsDropDown(mBinding.imgRight);
                selectPopupWindow.setOnItemClickListener(new SelectPopupWindow.OnItemClickListener() {

                    @Override
                    public void onItemClick(int positon) {
                        switch (positon) {
                            //拍照
                            case 0:
                                if (selectList != null) {
                                    selectList.clear();
                                }
                                CaremaPhotoUtils.goCarema(LookFragment.this, selectList, PictureMimeType.ofImage());
                                break;
                            //录视频
                            case 1:
                                if (selectList != null) {
                                    selectList.clear();
                                }
                                CaremaPhotoUtils.goCarema(LookFragment.this, selectList, PictureMimeType.ofVideo());
                                break;
                            //相册
                            case 2:
                                if (selectList != null) {
                                    selectList.clear();
                                }
                                CaremaPhotoUtils.goPhotos(LookFragment.this, selectList);
                                break;
                        }
                    }
                });
            }
        });

        mBinding.imgRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/look/editlook")
                        .withString("type", "8")
                        .navigation();
            }
        });
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_look;
    }

    private int firstVisible;//当前第一个可见的item
    private int visibleCount;//当前可见的item个数
    private VideoView videoView;

    /**
     * 滑动停止自动播放视频
     */
    private void autoPlayVideo1(RecyclerView view) {
        for (int i = 0; i < visibleCount; i++) {
            if (view != null && view.getChildAt(i) != null && view.getChildAt(i).findViewById(R.id.multi_video) != null) {
                videoView = (VideoView) view.getChildAt(i).findViewById(R.id.multi_video);
                Rect rect = new Rect();
                videoView.getLocalVisibleRect(rect);
                int videoheight3 = videoView.getHeight();

                if (rect.top == 0 && rect.bottom == videoheight3) {
                    videoView.start();
//                    if (videoPlayerStandard1.currentState == JCVideoPlayer.CURRENT_STATE_NORMAL || videoPlayerStandard1.currentState == JCVideoPlayer.CURRENT_STATE_ERROR) {
//                        Log.e("videoTest", videoPlayerStandard1.currentState + "======================performClick======================");
//                        videoPlayerStandard1.startButton.performClick();
//
//                    }
                    return;
                }

            }
        }
        //JCVideoPlayer.releaseAllVideos();
    }

    public int firstVisibleItem, lastVisibleItem;

    @Override
    public void start() {
        DataCenter.init();
        mBinding.emojiPanelView.initEmojiPanel(DataCenter.emojiDataSources);
        RxBus2.getInstance().post(new StatEntity(1));
        mPresenter.lookList(page, 20);
        linearLayoutManager = new LinearLayoutManager(mContext);
        mBinding.recycler.setLayoutManager(linearLayoutManager);
        lookAdapter = new LookAdapter2(mContext, mData, mPresenter.mUser.getUserId());
        mBinding.recycler.setAdapter(lookAdapter);
        mBinding.smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                mPresenter.lookList(page, 20);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                mPresenter.lookList(page, 20);
            }
        });
        mBinding.emojiPanelView.setOnTextListener(new EmojiPanelView.OnTextListener() {
            @Override
            public void listener(String str, LookListBean.Rows item, int position) {
                /**
                 * 评论
                 */
                if (TextUtils.isEmpty(str)) {
                    showMes("评论不能为空");
                    return;
                }
                comments = new LookListBean.Rows.Comments();
                comments.setToName("");
                comments.setContent(str);
                comments.setFromName(mPresenter.mUser.getUserName());
                comments.setType(0);
                mPresenter.addComment(0, "", str, item.getId(), position);
            }
        });
        mBinding.emojiPanelView.setOnTextRepListener(new EmojiPanelView.OnTextRepListener() {
            @Override
            public void listener(String id, String itemId, int position, String repey, String reviewName) {
                if (TextUtils.isEmpty(repey)) {
                    showMes("回复不能为空");
                    return;
                }
                reply = new LookListBean.Rows.Comments();
                reply.setToName(reviewName);
                reply.setContent(repey);
                reply.setFromName(mPresenter.mUser.getUserName());
                reply.setType(1);
                mPresenter.addComment(1, id, repey, itemId, position);
            }
        });
        //滚动监听
        mBinding.recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    autoPlayVideo1(recyclerView);
                    // Glide.with(mContext).resumeRequests();
                } else {
                    MediaPlayerManager.instance().pause();
                }

            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisible = linearLayoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                visibleCount = lastVisibleItem - firstVisibleItem;
                // Glide.with(mContext).pauseRequests();

            }
        });
        lookAdapter.setOnActionListener(new LookAdapter2.OnActionListener() {
            @Override
            public void onComment(LookListBean.Rows item, int position) {
                //showCommentDialog(item, position);
//                CommPopWindow commPopWindow = new CommPopWindow(getActivity());
//                commPopWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
//                commPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//                commPopWindow.showAsDropDown(mBinding.recycler);
                //ReplyBox(0, null, item, position, "请输入评论内容......");
                mBinding.emojiPanelView.setVisibility(View.VISIBLE);
                mBinding.emojiPanelView.showEmojiPanel(0, item, position, "请输入评论内容......");
            }

            @Override
            public void onHit(LookListBean.Rows item, int position) {
                //点赞
                mPresenter.thumbs(item.getId(), position);
            }

            @Override
            public void onDetailClick(LookListBean.Rows.Comments comments, LookListBean.Rows rows, int position) {
                if (mPresenter.mUser.getUserName().equals(comments.getFromName())) {
                    ToastUtil.show("不能回复自己的评论!");
                    return;
                }
                mBinding.emojiPanelView.setVisibility(View.VISIBLE);
                mBinding.emojiPanelView.showEmojiPanel(1, comments.getId(), rows.getId(), position, "回复 " + comments.getFromName() + " 的评论:", comments);
//                showReplyDialog(comments, rows,position);
//                mPresenter.addComment(1, comments.getId(), replyContent, rows.getId(),position);
            }

            @Override
            public void onAllReplyOpen(LookListBean.Rows item) {

            }

            /**
             * 删除
             * @param id
             */
            @Override
            public void onDeleteCommentsReplsys(LookListBean.Rows item, String id, int position) {
                item.getThumbIdList().remove(position);
                lookAdapter.notifyDataSetChanged();
            }

            @Override
            public void onUserIconClick(String userName) {
                ToastUtil.show(userName);
            }

            @Override
            public void onLongClick(LookListBean.Rows item) {

            }

            @Override
            public void onDeleteLookClick(final String id, final int position) {
                /**
                 * 删除自己发布的看看
                 */
                CommonDialog dialog = new CommonDialog(mContext, "您确定要删除吗？", "提示", "取消", "确定");
                dialog.setOnPosClick(new CommonDialog.OnPosClick() {
                    @Override
                    public void onClick() {
                        mPresenter.delete(id, position);
                    }
                });
                dialog.show();
            }
        });


        disposable = RxBus2.getInstance().doSubscribe(StatEntity2.class, new Consumer<StatEntity2>() {
            @Override
            public void accept(StatEntity2 bean) throws Exception {
                if (bean.getState() == 0X0000010) {
                    if (mPresenter != null) {
                        page = 1;
                        mPresenter.lookList(page, 20);
                    }
                }
            }
        });
        disposableEvent = RxBus2.getInstance().doSubscribe(MotionEvent.class, new Consumer<MotionEvent>() {
            @Override
            public void accept(MotionEvent motionEvent) throws Exception {
                TextLinkifyUtils.hideInputWhenTouchOtherView(_mActivity, motionEvent, getExcludeTouchHideInputViews());
            }
        });
        RxBus2.getInstance().addSubscription(this, disposable);
        RxBus2.getInstance().addSubscription(this, disposableEvent);
    }

    public List<View> getExcludeTouchHideInputViews() {
        List<View> views = new ArrayList<>();
        views.add(mBinding.emojiPanelView);
        return views;
    }


    @Override
    public void returnCommentReplySuccess(String SuccessMsg, int type, int position) {
        if (type == 0) {
            // mPresenter.lookList(page,10);
            if (comments != null) {
                mData.get(position).getComments().add(comments);
            }
            ToastUtil.show("评论成功");
        } else if (type == 1) {
            //mPresenter.lookList(page,10);
            if (reply != null) {
                mData.get(position).getComments().add(reply);
            }
            ToastUtil.show("回复成功");

        }
        lookAdapter.notifyDataSetChanged();
        if (mBinding.emojiPanelView.getVisibility() == View.VISIBLE) {
            mBinding.emojiPanelView.setVisibility(View.GONE);
        }

    }

    @Override
    public void returnCommentReplyError(String errMsg) {
        ToastUtil.show("出错了");
    }

    @Override
    public void returnLoolListSuccess(LookListBean lookListBean) {
        mBinding.empty.setVisibility(View.GONE);
        mBinding.smartRefreshLayout.finishRefresh();
        mBinding.smartRefreshLayout.setLoadmoreFinished(false);
        mData.clear();
        mData.addAll(lookListBean.getRows());
        lookAdapter.notifyDataSetChanged();
    }


    @Override
    public void returnNoData() {
        mBinding.smartRefreshLayout.finishRefresh();
        mBinding.empty.setVisibility(View.VISIBLE);
    }

    @Override
    public void returnMoreList(LookListBean lookListBean) {
        mBinding.empty.setVisibility(View.GONE);
        mBinding.smartRefreshLayout.finishLoadmore();
        mBinding.smartRefreshLayout.setLoadmoreFinished(false);
        mData.addAll(lookListBean
                .getRows());
        if (lookAdapter != null) {
            lookAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void returnNoMoreData() {
        mBinding.empty.setVisibility(View.GONE);
        mBinding.smartRefreshLayout.finishLoadmore();
        mBinding.smartRefreshLayout.setLoadmoreFinished(true);
    }

    @Override
    public void returnListError() {
        mBinding.empty.setVisibility(View.GONE);
        if (page == 1) {
            mBinding.smartRefreshLayout.finishRefresh();
        } else {
            mBinding.smartRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void returnThumbsSuccess(String msg, int position) {
        if (msg.contains("成功")) {
            if (!mData.get(position).getThumbIdList().toString().contains(mPresenter.mUser.getUserId())
                    && !mData.get(position).getThumbList().toString().contains(mPresenter.mUser.getUserName())) {
                mData.get(position).getThumbIdList().add(mPresenter.mUser.getUserId());
                mData.get(position).getThumbList().add(mPresenter.mUser.getUserName());
            }
        } else {
            if (mData.get(position).getThumbIdList() != null) {
                for (int i = 0; i < mData.get(position).getThumbIdList().size(); i++) {
                    if (mData.get(position).getThumbIdList().get(i).equals(mPresenter.mUser.getUserId())) {
                        mData.get(position).getThumbIdList().remove(i);
                        mData.get(position).setHit(false);
                    }
                }
            }

            if (mData.get(position).getThumbList() != null) {
                for (int i = 0; i < mData.get(position).getThumbList().size(); i++) {
                    if (mData.get(position).getThumbList().get(i).equals(mPresenter.mUser.getUserName())) {
                        mData.get(position).getThumbList().remove(i);
                    }
                }
            }
        }
        lookAdapter.notifyDataSetChanged();
        ToastUtil.show(msg);
    }

    @Override
    public void returnThumbsError(String msg) {
        ToastUtil.show("出错了");
    }

    /**
     * 删除看看成功后刷新
     *
     * @param msg
     * @param position
     */
    @Override
    public void returnDeleteSuccess(String msg, int position) {
        mData.remove(position);
        if (lookAdapter != null) {
            lookAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void returnDeleteError(String msg) {

    }

    /**
     * 弹出评论框
     */
    private void showCommentDialog(final LookListBean.Rows item, final int position) {
        dialog = new BottomSheetDialog(mContext);
        View commentView = LayoutInflater.from(mContext).inflate(R.layout.comment_dialog_layout, null);
        final EditText commentText = (EditText) commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = (Button) commentView.findViewById(R.id.dialog_comment_bt);
        dialog.setContentView(commentView);
        /**
         * 解决bsd显示不全的情况
         */
        View parent = (View) commentView.getParent();
        BottomSheetBehavior behavior = BottomSheetBehavior.from(parent);
        commentView.measure(0, 0);
        behavior.setPeekHeight(commentView.getMeasuredHeight());

        bt_comment.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                String commentContent = commentText.getText().toString().trim();
                if (!TextUtils.isEmpty(commentContent)) {
                    dialog.dismiss();
                    /**
                     * 评论
                     */
                    comments = new LookListBean.Rows.Comments();
                    comments.setToName("");
                    comments.setContent(commentContent);
                    comments.setFromName(mPresenter.mUser.getUserName());
                    comments.setType(0);
                    mPresenter.addComment(1, "", commentContent, item.getId(), position);
                } else {
                    Toast.makeText(mContext, "评论内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 0) {
                    bt_comment.setBackgroundColor(Color.parseColor("#0279e7"));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        dialog.show();
    }

    /**
     * 弹出回复框
     */
    private void showReplyDialog(final LookListBean.Rows.Comments item, final LookListBean.Rows rows, final int position) {
        dialog = new BottomSheetDialog(mContext);
        View commentView = LayoutInflater.from(mContext).inflate(R.layout.comment_dialog_layout, null);
        final EditText commentText = (EditText) commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = (Button) commentView.findViewById(R.id.dialog_comment_bt);
        commentText.setHint("回复 " + item.getFromName() + " 的评论:");
        dialog.setContentView(commentView);
        bt_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String replyContent = commentText.getText().toString().trim();
                if (!TextUtils.isEmpty(replyContent)) {

                    dialog.dismiss();
                    comments = new LookListBean.Rows.Comments();
                    comments.setToName(item.getFromName());
                    comments.setContent(replyContent);
                    comments.setFromName(mPresenter.mUser.getUserName());
                    comments.setType(1);
                    /**
                     * 回复
                     */
                    mPresenter.addComment(1, item.getId(), replyContent, rows.getId(), position);
                } else {
                    Toast.makeText(mContext, "回复内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 0) {
                    bt_comment.setBackgroundColor(Color.parseColor("#0279e7"));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        dialog.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            disposable.dispose();
        }
        if (disposableEvent != null) {
            disposableEvent.dispose();
        }
        if (mPresenter != null) {
            mPresenter.release();
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            RxBus2.getInstance().post(new StatEntity(1));
        }
        //fragment  hide的时候暂停播放视频   显示的时候重新播放
        if (hidden) {
            MediaPlayerManager.instance().pause();
        } else {
            MediaPlayerManager.instance().start();
        }
    }

    private List<LocalMedia> selectList = new ArrayList<>();

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    Gson gson = new Gson();
                    String json = gson.toJson(selectList);
                    ARouter.getInstance().build("/look/editlook")
                            .withString("images", json)
                            .withString("type", "2")
                            .navigation();
                    break;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MediaPlayerManager.instance().start();

    }

    @Override
    public void onStop() {
        super.onStop();
        MediaPlayerManager.instance().pause();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private PopupWindow mpopupWindow;
    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (mpopupWindow != null) {
                    mpopupWindow.dismiss();
                }
                return true;
            }

            return false;
        }
    };


    /**
     * 显示键盘
     *
     * @param text 输入焦点
     */
    private void showSoft(final EditText text) {
        Handler handle = new Handler();
        handle.postDelayed(new Runnable() {

            @Override
            public void run() {
                InputMethodManager inputMethodManager = (InputMethodManager) text.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(text, 0);
            }
        }, 0);
    }

    private void popupInputMethodWindow() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override

            public void run() {
                InputMethodManager imm = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }, 0);

    }

}
